package com.hesicare.cgm.worker;

import com.hesicare.cgm.entity.CgmPatient;
import com.hesicare.cgm.entity.CgmPatientDTO;
import com.hesicare.cgm.entity.CgmPatientGlucose;
import com.hesicare.cgm.enums.CgmEnum;
import com.hesicare.config.cache.Cache;
import com.hesicare.untils.httpUtils.HttpUtils;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Author 55097
 * @create 2021/12/6 18:18
 */
@Component
public class CgmInteractive {

    @Value("${CGMurl}")
    private String cgmUrl;

    @Autowired
    private Cache cache;

    private static String failCode = "401";

    public synchronized String getCgmToken() {
        Map login = new HashMap();
        login.put("username", "admin");
        login.put("password", "admin123");
        String content = HttpUtils.doPostWithToken(cgmUrl + "/app/user/login", login);
        JSONObject object = JSONObject.fromObject(content);
        String token = object.getJSONObject("data").get("token").toString();
        cache.put(CgmEnum.CGMTOKEN, token);
        return token;
    }

    public String pullCgmBlood(CgmPatientDTO cgmPatientDTO) {
        String result = HttpUtils.doPostWithJson(cgmUrl + "/api/thirdPart/glucose/pull", new org.apache.commons.beanutils.BeanMap(cgmPatientDTO), cache.get(CgmEnum.CGMTOKEN).toString());
        JSONObject object = JSONObject.fromObject(result);
        if (failCode.equals(object.getString("code"))) {
            getCgmToken();
            return pullCgmBlood(cgmPatientDTO);
        }
        return object.get("data").toString();
    }

    public String pushCgmBlood(CgmPatient cgmPatient) {
        String result = HttpUtils.doPostWithJson(cgmUrl + "/api/thirdPart/patient/push", new org.apache.commons.beanutils.BeanMap(cgmPatient), cache.get(CgmEnum.CGMTOKEN).toString());
        JSONObject object = JSONObject.fromObject(result);
        if (failCode.equals(object.getString("code"))) {
            getCgmToken();
            return pushCgmBlood(cgmPatient);
        }
        return object.get("data").toString();
    }

}
